import { ListNode } from "./utils";

export function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    // 指向头结点的引用
    let pl1 = l1;
    let pl2 = l2;
    // 是否有进位
    let carry: 0 | 1 = 0;
    // 虚拟头结点
    const vHead = new ListNode();
    // 当前结果结点
    let cur = vHead;
    while (pl1 && pl2) {
        sum(pl1.val, pl2.val);

        pl1 = pl1.next;
        pl2 = pl2.next;
    }
    while (pl1) {
        sum(pl1.val, 0);
        pl1 = pl1.next;
    }
    while (pl2) {
        sum(0, pl2.val);
        pl2 = pl2.next;
    }

    // 如果此时 carry 为 1 ，还需要加1位
    if (carry !== 0) {
        cur.next = new ListNode(1);
    }

    function sum (val1: number, val2: number) {
        let sum = val1 + val2 + carry;
        carry = (sum > 9) ? 1 : 0;
        sum = sum % 10;
        cur.next = new ListNode(sum);
        cur = cur.next;
    }


    return vHead.next;
};



